import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '@/pages/HomePage.vue'
import DocsPage from '@/pages/DocsPage.vue'
import UserCenterPage from '@/pages/user/UserCenterPage.vue'
import UserManagePage from '@/pages/admin/UserManagePage.vue'
import AppManagePage from '@/pages/admin/AppManagePage.vue'
import ChatHistoryManagePage from '@/pages/admin/ChatHistoryManagePage.vue'
import AppChatPage from '@/pages/app/AppChatPage.vue'
import AppDetailPage from '@/pages/app/AppDetailPage.vue'
import AppEditPage from '@/pages/app/AppEditPage.vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { message } from 'ant-design-vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: '主页',
      component: HomePage,
    },
    {
      path: '/docs',
      name: '使用文档',
      component: DocsPage,
    },
    {
      path: '/user/center',
      name: '个人中心',
      component: UserCenterPage,
      meta: { requiresAuth: true },
    },
    {
      path: '/admin/userManage',
      name: '用户管理',
      component: UserManagePage,
      meta: { requiresAuth: true, requiresAdmin: true },
    },
    {
      path: '/admin/appManage',
      name: '应用管理',
      component: AppManagePage,
      meta: { requiresAuth: true, requiresAdmin: true },
    },
    {
      path: '/admin/chatHistoryManage',
      name: '对话管理',
      component: ChatHistoryManagePage,
      meta: { requiresAuth: true, requiresAdmin: true },
    },
    {
      path: '/app/chat/:id',
      name: '应用对话',
      component: AppChatPage,
      meta: { requiresAuth: true },
    },
    {
      path: '/app/detail/:id',
      name: '应用详情',
      component: AppDetailPage,
    },
    {
      path: '/app/edit/:id',
      name: '编辑应用',
      component: AppEditPage,
      meta: { requiresAuth: true },
    },
  ],

})

/**
 * 路由守卫：检查登录状态和权限
 */
router.beforeEach(async (to, from, next) => {
  const loginUserStore = useLoginUserStore()
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    // 如果没有用户信息，先尝试获取
    if (!loginUserStore.loginUser.id) {
      try {
        await loginUserStore.fetchLoginUser()
      } catch (error) {
        console.log('获取用户信息失败，跳转到登录页面')
      }
    }
    
    // 再次检查用户是否已登录
    if (!loginUserStore.loginUser.id) {
      message.error('请先登录')
      loginUserStore.openLoginModal()
      next('/')
      return
    }
  }
  
  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin) {
    if (loginUserStore.loginUser.userRole !== 'admin') {
      message.error('您没有权限访问该页面')
      next('/')
      return
    }
  }
  
  next()
})

export default router
